const got = require('got')
const {Menu,dialog} = require('electron')
const path = require("path");
const fs = require('fs')
const imageType = require('image-type')
const {acceptHMRUpdate} = require("pinia");
const saveas = (url) => {
    if(url){
        const contextMenu = Menu.buildFromTemplate([
            {
                label:'图片另存为..',
                click:async ()=>{
                    try{
                        const res = await got.get(url)
                        const chunk = Buffer.from(res.rawBody)
                        const imgType = imageType(chunk)
                        const {canceled,filePath} = await dialog.showSaveDialog({
                            title:'图片另存为',
                            defaultPath:path.resolve(__dirname,'../public/upload/' + new Date().getTime() + '.' + imgType.ext)
                        })
                        if(!canceled){
                            fs.writeFileSync(filePath,chunk)
                        }
                    }catch (e){

                    }
                },
                accelerator:'ctrl+k'
            },

        ])

        contextMenu.popup()
    }
}

module.exports = saveas